package com.ruoyi.web.controller.purchase;

/**
 * @Author: 黄佳成
 * @Date: 2022/1/5
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.purchase.domain.*;
import com.ruoyi.purchase.service.DetailService;
import com.ruoyi.purchase.service.ProductService;
import com.ruoyi.purchase.service.PurchaseService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 采购单管理
 */
@Controller
@RequestMapping("/purchase/repo")
public class RepoPurchaseController extends BaseController {
    // 方法返回值前缀
    private String prefix = "purchase/repo";
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private ProductService productService;
    @Autowired
    private DetailService detailService;

    // 品牌管理 左侧菜单栏
    @RequiresPermissions("purchase:repo:view")
    @GetMapping()
    public String repo() {
        return prefix + "/purchase";
    }

    /**
     * 查询品牌信息列表
     */
    @RequiresPermissions("purchase:repo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Purchase purchase)
    {
        startPage();
        List<Purchase> list = purchaseService.queryList(purchase);
        return getDataTable(list);
    }

    /**
     * 导出品牌信息列表
     */
    @RequiresPermissions("purchase:repo:export")
    @Log(title = "品牌信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Purchase purchase)
    {
        List<Purchase> list = purchaseService.queryList(purchase);
        ExcelUtil<Purchase> util = new ExcelUtil<Purchase>(Purchase.class);
        return util.exportExcel(list, "purchase");
    }

    /**
     * 品牌信息信息  跳转到添加页面
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        SysUser user = getSysUser();//当前登录用户信息
        mmap.put("user",user);
        return prefix + "/add";
    }

    /**
     * 新增保存订购单信息
     */
    @RequiresPermissions("purchase:repo:add")
    @Log(title = "品牌信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(PurchaseDemo purchaseDemo) {
        Purchase purchase=new Purchase();
        purchase.setPurId(purchaseDemo.getPurId());
        purchase.setSysCreateUserId(purchaseDemo.getSysCreateUserId());
        purchase.setStatus(purchaseDemo.getStatus());
        purchase.setTotal(purchaseDemo.getTotal());
        purchase.setPurTime(purchaseDemo.getPurTime());
        List<DetailDemo> detailDemoList = purchaseDemo.getDetailDemoList();
        for (DetailDemo detailDemo:detailDemoList) {
            System.out.println(detailDemo);
        }

        for (DetailDemo detailDemo : purchaseDemo.getDetailDemoList()) {
            Product product = productService.findByBrandTypeModel(detailDemo.getProductModel());
            Detail detail=new Detail();
            detail.setPoPurId(purchaseDemo.getPurId());
            detail.setPoProductId(product.getProductId());
            detail.setNum(detailDemo.getNum());
            detail.setBuyPrice(detailDemo.getPrice());
            detail.setTotal(detailDemo.getMoney());
            System.out.println(detail);
            boolean flag = detailService.save(detail);
            System.out.println(flag);


        }
        return toAjax(purchaseService.save(purchase));
    }


    /**
     * 修改品牌信息 跳转到修改页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String purId, ModelMap mmap) throws JsonProcessingException
    {
        Purchase purchase = purchaseService.findPurchase(purId);
        System.out.println(purId);
        List <Detail>detailList = detailService.findDetailById(purId);
        List<Product> productList=new ArrayList<>();
        for (Detail detail:detailList) {
            Product product=productService.getById(detail.getPoProductId());
            productList.add(product);
        }
        List<DetailDemo> detailDemoList=new ArrayList<>();

        Integer size=detailList.size();
        for (Integer i=0;i<size;i++ ) {
            DetailDemo detailDemo=new DetailDemo();
            detailDemo.setNum(detailList.get(i).getNum());
            detailDemo.setPrice(detailList.get(i).getBuyPrice());
            detailDemo.setMoney(detailList.get(i).getTotal());
            detailDemo.setBrandId(productList.get(i).getBrandId());
            detailDemo.setTypeId(productList.get(i).getPoTypeId());
            detailDemo.setProductModel(productList.get(i).getProductModel());
            detailDemo.setFirmId(productList.get(i).getPoFirmId());
            detailDemo.setUnit(productList.get(i).getUnit());
            detailDemo.setDetailId(detailList.get(i).getDetailId());
            detailDemoList.add(detailDemo);
        }
        mmap.put("productList",productList);
        mmap.put("detailList",detailList);

        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(detailDemoList);
        mmap.addAttribute("detailDemoList", jsonStr);
        SysUser user = getSysUser();//当前登录用户信息
        mmap.put("user",user);
        mmap.put("purchase",purchase);

        return prefix + "/edit";
    }

    /**
     * 修改保存品牌信息
     */
    @RequiresPermissions("purchase:repo:edit")
    @Log(title = "采购单信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PurchaseDemo purchaseDemo)
    {
        Purchase purchase=new Purchase();
        purchase.setPurId(purchaseDemo.getPurId());
        purchase.setSysCreateUserId(purchaseDemo.getSysCreateUserId());
        purchase.setStatus(purchaseDemo.getStatus());
        purchase.setTotal(purchaseDemo.getTotal());
        purchase.setPurTime(purchaseDemo.getPurTime());
        List<DetailDemo> detailDemoList = purchaseDemo.getDetailDemoList();
        for (DetailDemo detailDemo:detailDemoList) {
            System.out.println(detailDemo);
        }

        for (DetailDemo detailDemo : purchaseDemo.getDetailDemoList()) {
            Product product = productService.findByBrandTypeModel(detailDemo.getProductModel());
            Detail detail=new Detail();
            detail.setPoPurId(purchaseDemo.getPurId());
            detail.setPoProductId(product.getProductId());
            detail.setNum(detailDemo.getNum());
            detail.setBuyPrice(detailDemo.getPrice());
            detail.setTotal(detailDemo.getMoney());
            detail.setDetailId(detailDemo.getDetailId());
            System.out.println(detail);
            boolean flag = detailService.modify(detail);
            System.out.println(flag);
        }
        return toAjax(purchaseService.updateById(purchase));
    }
    /**
     * 提交审核信息 跳转到提交审核页面
     */
    @GetMapping("/check/{bid}")
    public String check(@PathVariable("bid") String bid, ModelMap mmap)
    {
        mmap.put("purId", bid);
        return prefix + "/check";
    }
    /**
     * 提交审核保存信息
     */
    @RequiresPermissions("purchase:repo:check")
    @Log(title = "采购单信息", businessType = BusinessType.UPDATE)
    @PostMapping("/check")
    @ResponseBody
    public AjaxResult checkSave( Purchase purchase)
    {
        return toAjax(purchaseService.updatePurchaseby(purchase));
    }

    /**
     * 详情 跳转到详情页面
     */
    @GetMapping("/details/{bid}")
    public String details(@PathVariable("bid") String bid, ModelMap mmap)
    {
        Purchase purchase = purchaseService.findPurchase(bid);
        mmap.put("purchase", purchase);
        return prefix + "/details";
    }

    /**
     * 入库详情 跳转到入库详情页面
     */
    @GetMapping("/put/{bid}")
    public String put(@PathVariable("bid") String bid, ModelMap mmap)
    {
        Purchase purchase = purchaseService.findPurchase(bid);
        mmap.put("purchase", purchase);
        return prefix + "/put";
    }



    /**
     * 删除品牌信息
     */
    @RequiresPermissions("purchase:repo:remove")
    @Log(title = "采购单信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        if (ArrayUtils.contains(Convert.toStrArray(ids), getUserId()))
        {
            return error("当前采购单不能删除");
        }
        return toAjax(purchaseService.deleteUserByIds(ids));
    }

}
